<template>
  <div class="chat-page">
    <van-nav-bar
      :title="detail.doctorName || '医生'"
      left-arrow
      @click-left="router.back()"
      fixed
    />

    <!-- 聊天内容区域 -->
    <div class="chat-container" ref="chatContent">
      <div class="chat-list">
        <template v-for="msg in detail.messages" :key="msg.id">
          <!-- 系统消息 -->
          <div v-if="msg.type === 'system'" class="system-message">
            {{ msg.content }}
          </div>
          <!-- 聊天消息 -->
          <div
            v-else
            class="message"
            :class="isCurrentUserMessage(msg.type) ? 'message-right' : 'message-left'"
          >
            <van-image
              round
              width="40"
              height="40"
              :src="isCurrentUserMessage(msg.type) ? detail.userAvatar : detail.doctorAvatar"
            />
            <div class="message-content">
              <div class="message-text">
                {{ msg.content }}
              </div>
              <div class="message-time">{{ formatTime(msg.createTime) }}</div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <van-field
        v-model="inputMessage"
        placeholder="请输入内容"
        :border="false"
        @keypress.enter.prevent="sendMess"
        :autosize="{ maxHeight: 100, minHeight: 20 }"
        type="textarea"
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            :disabled="!inputMessage.trim()"
            @click="sendMess"
            round
          >
            发送
          </van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { getConsultationDetail, sendMessage } from '@/api/consultation'
import defaultAvatar from '@/assets/default-avatar.png'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const consultationId = route.params.id
const inputMessage = ref('')
const chatContent = ref(null)
const detail = ref({
  doctorName: '',
  doctorAvatar: '',
  userAvatar: '',
  messages: []
})

// 加载问诊详情
const loadConsultationDetail = async () => {
  try {
    const res = await getConsultationDetail(consultationId)
    if (res.code === 200 && res.data) {
      detail.value = res.data
      scrollToBottom()
    } else {
      showToast(res.message || '获取问诊详情失败')
    }
  } catch (error) {
    console.error('获取问诊详情失败:', error)
    showToast('获取问诊详情失败')
  }
}

// 发送消息
const sendMess = async () => {
  if (!inputMessage.value.trim()) {
    return
  }

  try {
    const res = await sendMessage(consultationId, {
      content: inputMessage.value,
      type: 'user'
    })

    if (res.code === 200) {
      // 添加新消息到列表
      detail.value.messages.push({
        id: res.data,  // 后端返回的消息ID
        content: inputMessage.value,
        fromUserId: userStore.userId,
        type: 'user',
        createTime: new Date().toISOString()
      })

      inputMessage.value = ''
      scrollToBottom()
    } else {
      showToast(res.message || '发送失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    showToast('发送失败')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 判断是否是当前用户的消息
const isCurrentUserMessage = (msgType) => {
  return msgType === 'user'
}

onMounted(() => {
  loadConsultationDetail()
})
</script>

<style lang="scss" scoped>
.chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;

  :deep(.van-nav-bar) {
    background-color: #fff;

    .van-nav-bar__title {
      font-size: 16px;
      font-weight: 500;
    }
  }
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 56px 12px 0;
  -webkit-overflow-scrolling: touch;

  .chat-list {
    padding: 12px;
  }

  .system-message {
    text-align: center;
    margin: 12px 0;
    font-size: 12px;
    color: #999;
  }

  .message {
    display: flex;
    margin-bottom: 20px;
    align-items: flex-start;

    &.message-left {
      .message-content {
        margin-left: 12px;
        .message-text {
          background-color: #fff;
          border-radius: 4px 12px 12px 12px;
        }
      }
    }

    &.message-right {
      flex-direction: row-reverse;
      .message-content {
        margin-right: 12px;
        .message-text {
          background-color: #95ec69;
          border-radius: 12px 4px 12px 12px;
        }
        .message-time {
          text-align: right;
        }
      }
    }

    .message-content {
      max-width: 70%;

      .message-text {
        padding: 10px 12px;
        font-size: 14px;
        line-height: 1.5;
        word-break: break-all;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
      }

      .message-time {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
      }
    }
  }
}

.chat-input {
  padding: 10px 12px;
  background: #fff;
  border-top: 1px solid #ebedf0;

  :deep(.van-field) {
    background-color: #f7f8fa;
    border-radius: 4px;
    padding: 4px 8px;

    .van-field__control {
      font-size: 14px;
      min-height: 20px;
    }
  }

  :deep(.van-field__button) {
    margin-left: 8px;

    .van-button {
      height: 32px;
      line-height: 30px;
      font-size: 14px;
    }
  }
}
</style>
